package io.github.annyylxyms.gyn.gateway.web.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * gateway web filter
 * @author annyylxyms
 */
@Component
public class GatewayWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        System.out.println("===>>>>> GYN Gateway web filter ...");
        //这里可以干任何事，比如：记录日志、鉴权、限流、流量转发等等
        //以一个前置处理为例：访问请求路径中加个?mock=true，做mock返回，不让调真实接口这件事

        if(exchange.getRequest().getQueryParams().getFirst("mock")==null){
            //如果为空，让chain继续往下走，去调用别的filter
            return chain.filter(exchange);
        }
        String mock = """
                {"result":"mock"}
                """;
        return exchange.getResponse()
                .writeWith(Mono.just(exchange.getResponse()
                        .bufferFactory().wrap(mock.getBytes())));
    }
}
